<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
    <title>课程-任务</title>

    <%@ include file="/common/commonLib.jsp" %>
    <link rel="stylesheet" type="text/css" href="<c:url value='/css/courseTaskEdit.css'/>"/>
    <link rel="stylesheet" type="text/css" href="<c:url value='/css/common-main.css'/>"/>
    <link rel="stylesheet" type="text/css" href="<c:url value='/wangEditor/dist/css/wangEditor.css'/>"/>
    <link rel="stylesheet" type="text/css" href="<c:url value='/css/checkboxcss/inserthtml.com.radios.css'/>"/>
    <script src="<c:url value='/js/taskEdit.js'/>" type="text/javascript" charset="utf-8"></script>

</head>
<body>
<div class="container-fluid main">
    <div class="row">
        <div class="col-md-12">
            <%@include file="/common/header.jsp" %>
        </div>
        <div class="col-md-12">
            <%@include file="common/courseHeader.jsp" %>
        </div>
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-3">
                    <%@include file="common/courseLeft.jsp" %>
                </div>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-12">
                            <%@include file="common/courseNavbar.jsp" %>
                        </div>

                        <div class="col-md-12">
                            <div class="tab-nav">
                                <a id="href1" class="front-nav" title="返回任务首页">任务首页
                                </a>&nbsp;>&nbsp;<span id="href2" class="back-nav"></span>
                            </div>
                            <div class="row taskEdit">
                                <div class="col-md-12">
                                    <hr>
                                    <!-- 任务名 -->
                                    <div class="form-group">
                                        <label for="">任务名称</label>
                                        <input type="hidden" name="detailTaskId"/>
                                        <span id="edit-task-name" title="任务名称"></span>
                                    </div>

                                    <div class="form-group">
                                        <label for="">任务类型</label>
                                        <span id="task-type" title="任务类型"></span>
                                        <input type="hidden" name="hiddenType"/>
                                        <select class="form-control" hidden="hidden" style="width: 160px;display:none"
                                                id="edit-task-type">
                                            <option value="ASKINLESSON">课堂提问</option>
                                            <option value="TESTINLESSON">当堂测试</option>
                                            <option value="HOMEWORK">课后作业</option>
                                            <option value="LABTEST">实验任务</option>
                                            <option value="PERSONALTASK">个人任务</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="">任务满分</label>
                                        <span id="task-full-mark" title="任务满分"></span>
                                        <input type="hidden" id="isSelect"/>
                                    </div>
                                    <hr>

                                    <div class="row">
                                        <div class="col-md-12">
                                            <label for="">任务描述</label>
                                        </div>
                                        <div class="col-md-12">
                                            <div id="editor-task">

                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-12">
                                            <label for="">任务附件</label>
                                            <button type="button" class="btn btn-primary"
                                                    onclick="$('#task-file-edit').click();">选择文件
                                            </button>
                                        </div>
                                        <div class="col-md-12" style="display:none;">
                                            <input type="file" id="task-file-edit" name="file"
                                                   onchange="taskFileListEdit()"/>
                                        </div>
                                        <div class="col-md-12">
                                            <ul id="task-file-list-edit">

                                            </ul>
                                        </div>
                                    </div>
                                    <hr>
                                    <div class="row">
                                        <div id="option" class="col-md-6">
                                            <label>答案选项</label>
                                            <table id="optionList">
                                            </table>
                                        </div>
                                        <div id="scoreItems" class="col-md-6">
                                            <label>评分项</label>
                                            <table id="scoreItemList">
                                                <tr>
                                                    <td class="col-md-7"><span style="font-weight: bold">评分项</span></td>
                                                    <td class="col-md-3"><span style="font-weight: bold">该项满分</span>
                                                    </td>
                                                    <td class="col-md-2"></td>
                                                </tr>

                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <label>课程目标权重</label>
                                            <div id="courseTarget-list">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-12">
                                            <span id="checkboxTitle" style="color:#00b43c;font-weight:bolder;"
                                                  title="点击显示答案">显示答案</span>
                                            <input type="checkbox" id="checkbox"/><label for="checkbox"
                                                                                         title="点击显示答案"></label>
                                        </div>
                                    </div>

                                    <div class="row" id="answer-box">
                                        <div class="col-md-12">
                                            <label>标准答案</label>
                                            <div id="editor-answer" style="min-height:15rem;">

                                            </div>
                                        </div>
                                        <div class="col-md-12">
                                            <label for="">标准答案附件</label>
                                            <button type="button" class="btn btn-primary"
                                                    onclick="$('#answer-file-edit').click();">选择文件
                                            </button>
                                        </div>
                                        <div class="col-md-12" style="display:none;">
                                            <input type="file" id="answer-file-edit" name="file"
                                                   onchange="answerFileListEdit()"/>
                                        </div>
                                        <div class="col-md-12">
                                            <ul id="answer-file-list-edit">

                                            </ul>
                                        </div>
                                    </div>

                                </div>
                            </div>
                            <div class="row" style="margin-top:2rem;">
                                <div class="col-md-4"></div>
                                <div class="col-md-4">
                                    <input type="number" id="count" style="display:none;" value="0">
                                    <input type="button" id="delete-task-btn" value="删除" class="btn btn-danger"
                                           title="点击删除任务"/>


                                    <input type="button" id="edit-task-btn" value="编辑" class="btn btn-primary"
                                           title="点击修改任务信息"/>
                                    <input type="button" id="publish-task-btn" value="分配和记录" class="btn btn-success"
                                           title="点击进行分配任务和查看记录"/>


                                </div>
                                <div class="col-md-4"></div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>

    </div>


</div>
<%@include file="/common/footer.jsp" %>
<script src="<c:url value='/wangEditor/dist/js/wangEditor.js'/>" type="text/javascript" charset="utf-8"></script>
</body>
<script>
    var data =${data};
    $(document).ready(function () {

        if (data.status != "success") {
            alert(data.message);
            return;
        }
        console.log(data.data)

        //删除任务
        $("#delete-task-btn").click(function () {
            var id = $("input[name='detailTaskId']").val();
            if (window.confirm("您确定要删除吗?")) {

                $.post(CONTEXT_PATH + "task/ajaxDelete", "id=" + id, function (data) {
                    if (data.status == "success") {

                        layer.msg("删除成功");
                        window.location = CONTEXT_PATH + "task/list?courseId=" + data.data.task.courseId
                    } else {
                        layer.msg("删除失败");
                    }
                });

            } else {

            }
        })

        $("#task").css("color", "#00b43c");
        $("#answer-box").hide();
        changeUrl(data.data.courseId);
        fetchCourse(data.data.courseId);
        initDetail(data.data.task);


        var count = $("#count").val();
        if (count == 0) {
            $("#editor-task").attr("contenteditable", false);
            $("#editor-answer").attr("contenteditable", false);
        }
        $("#checkbox").click(function () {
            if ($("#checkbox").is(":checked")) {
                $("#answer-box").show();
            } else {
                $("#answer-box").hide();
            }
        });
        $("#checkboxTitle").click(function () {
            if ($("#checkbox").is(":checked")) {
                $("#checkbox").attr("checked", false);
                $("#answer-box").hide();
            } else {
                $("#checkbox").attr("checked", true);
                $("#answer-box").show();
            }
        });
        $("#href1").attr("href", CONTEXT_PATH + "task/list?courseId=" + data.data.courseId);
        $("#href2").text(data.data.task.title);
    })

    var initDetail = function (view) {
        var taskType = getTaskType(view.type);
        $("input[name='hiddenType']").val(view.type);

        $("#task-type").text(taskType);
        // $("#edit-task-type").val(getType(view.type));
        $("#edit-task-type").val(view.type);
        $("#edit-task-name").text(isNull(view.title));
        $("input[name='detailTaskId']").val(view.id);
        $("#editor-task").html(isNull(view.description));
        $("#editor-answer").html(isNull(view.standardAnswer));
        initFileList(view.attachment.files, "attach", view.type);
        initFileList(view.answerAttachment.files, "anwserAttach", view.type);

        //新加
        $("#isSelect").val(view.isSelect);
        $("#task-full-mark").text(view.fullMark);

        console.log("11111111  "+view.fullMark);
        if (view.isSelect) {
            //选择题
            $("#option").show();
            $("#scoreItems").hide();
            var options = JSON.parse(view.content);
            var str = "";
            for (var i = 0; i < options.length; i++) {
                str += ("<tr class=\"option\">");
                str += ("<td class=\"col-md-2\"><span style=\"font-weight:bold\">") + options[i].num + ("</span></td>");
                str += ("<td class=\"col-md-8\"><input class=\"form-control readonly\" name=\"optionItem\" readonly=\"readonly\" value=\"") + options[i].item + ("\"></td>");
                str += ("</tr>");
            }
            $("#optionList").append(str);

        } else {
            //非选择题
            $("#option").hide();
            $("#scoreItems").show();
            var str = "";
            for (var i = 0; i < view.scoreItems.length; i++) {
                str += ("<tr class=\"scoreItem\">");
                str += ("<td class=\"col-md-7\"><input class=\"form-control readonly\" name=\"scoreItem\" readonly=\"readonly\" value=\"")
                    + view.scoreItems[i].scoreItem + ("\"></td>");
                str += ("<td class=\"col-md-3\"><input class=\"form-control readonly\" name=\"scoreItemWeight\" readonly=\"readonly\" value=\"")
                    + view.scoreItems[i].weight + ("\"></td>");
                str += ("<td class=\"col-md-2\"></td>");
                str += ("</tr>");
            }
            $("#scoreItemList").append(str);
        }
        var str = "";
        for (var i = 0; i < view.courseTargets.length; i++) {
            str += ("<div>");
            str += ("<span style=\"font-weight:bold;display: inline-block;width: 40%\">课程目标") + (i + 1) + ("权重：</span>");
            str += ("<input type=\"text\" name=\"courseTargetId\" hidden=\"hidden\" value=\"") + view.courseTargets[i].courseTargetId + ("\">");
            str += ("<input class=\"form-control readonly\" style=\"display: inline-block;width: 30%\" name=\"weight\" readonly=\"readonly\" value=\"")
                + view.courseTargets[i].weight + ("\">");
            str += ("</div>");
        }
        $("#courseTarget-list").append(str);
    }


    var getTaskType = function (type) {
        if (type == "ASKINLESSON") {
            return "课堂提问";
        } else if (type == "TESTINLESSON") {
            return "当堂测试";
        } else if (type == "HOMEWORK") {
            return "课后作业";
        } else if (type == "LABTEST") {
            return "实验任务";
        } else {
            return "个人任务";
        }
    }

    function getType(type) {
        if (type == "ASKINLESSON") return 0;
        if (type == "TESTINLESSON") return 1;
        if (type == "HOMEWORK") return 2;
        if (type == "LABTEST") return 3;
        if (type == "PERSONALTASK") return 4;
    }

    var isNull = function (string) {
        if (string == null || string.trim() == "" || string.trim() == "<p><br></p>") {
            return "(没有提供描述)";
        } else {
            return string.trim();
        }
    }

    var addAttachment = function (attachType) {
        var taskType = $("input[name='hiddenType']").val();
        var id = "";
        if (attachType == "attach") {//附件
            id = "task-file-edit"
        } else {//答案
            id = "answer-file-edit"
        }
        $.ajaxFileUpload({
            url: CONTEXT_PATH + "resource/upload", //用于文件上传的服务器端请求地址
            secureuri: false, //是否需要安全协议，一般设置为false
            fileElementId: id, //文件上传域的ID
            dataType: 'json', //返回值类型 一般设置为json
            success: function (data, status) //服务器成功响应处理函数
            {
                if (data.status == "success") {
                    ajaxAddAttachment(data.data, attachType, taskType);
                } else {
                    alert(data.message);
                }
            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
                alert(e);
            }
        });
    }

    var ajaxAddAttachment = function (data, attachType, taskType) {
        var id = $("input[name='detailTaskId']").val();
        var type = attachType == "attach" ? 1 : 2;
        var json = {
            id: id,
            type: type,
            name: data.name,
            key: data.key
        };

        $.post(CONTEXT_PATH + "task/ajaxAddAttachment", {
            data: JSON.stringify(json)
        }, function (data) {
            if (data.status == "success") {
                layer.msg("上传成功");
                initEditFileList(data.data.attachments, attachType);
            } else {
                alert(data.message);
            }
        });

    }

    var initEditFileList = function (list, attachType) {
        var obj = null;
        if (attachType == "attach") {
            obj = $("#task-file-list-edit");
        } else {
            obj = $("#answer-file-list-edit");
        }
        obj.empty();
        if (list.length <= 0) {
            var temp = "";
            temp += "<li class=\"no-attach\"><span>（未包含附件）</span></li>";
            obj.append(temp);
        } else {
            for (var i = 0; i < list.length; i++) {
                var temp = "";

                temp += ("<li><span>" + list[i].name + "</span>");
                temp += ("<button type=\"button\" style=\"display:block;\" class=\"btn btn-default\" onclick=\"deleteAttachment('" + list[i].url + "','" + attachType + "')\">删除</button></li>");

                obj.append(temp);
            }
        }
    }

    var deleteAttachment = function (key, attachType) {
        var type = attachType == "attach" ? 1 : 2;
        var json = {
            id: $("input[name='detailTaskId']").val(),
            type: type,
            key: key
        };

        $.post(CONTEXT_PATH + "task/ajaxDeleteAttachment", {
            data: JSON.stringify(json)
        }, function (data) {
            if (data.status == "success") {
                layer.msg("删除成功");
            } else {
                layer.msg("删除失败");
            }
        });
    }

    var initFileList = function (list, attachType) {
        var obj = null;
        if (attachType == "attach") {
            obj = $("#task-file-list-edit");
        } else {
            obj = $("#answer-file-list-edit");
        }
        obj.empty();
        if (list.length <= 0) {
            var temp = "";
            temp += "<li class=\"no-attach\"><span>（未包含附件）</span></li>";
            obj.append(temp);
        } else {
            for (var i = 0; i < list.length; i++) {
                var temp = "";
                temp += ("<li>");
                temp += ("<span>" + list[i].name + "</span>");
                temp += ("<a id=\"download-url\" href=\"/CourseSupport/resource/download/" + list[i].url + "\">下载</a>");
                temp += ("<button type=\"button\" style=\"\" class=\"btn btn-default\" onclick=\"deleteAttachment('" + list[i].url + "','" + attachType + "')\" >删除</button>");
                temp += ("</li>");
                obj.append(temp);
            }
        }
    }
    var removeWu = function (string) {
        string = string.trim();
        if (string == "(无)<p><br></p>" || string.indexOf("(无)") != -1) {
            string = string.replace("(无)", "");
            return string.replace("<p><br></p>", "");
        } else {
            return string.replace("<p><br></p>", "");
        }

    }
    var updateTaskDetail = function (taskEdit, answerEdit) {
        // var type=$("input[name='hiddenType']").val();
        var title = $("#edit-task-name").text();
        var id = $("input[name='detailTaskId']").val();
        var description = removeWu(taskEdit);
        var standardAnswer = removeWu(answerEdit);
        var type = $("#edit-task-type").val();
        var isSelect = $("#isSelect").val();
        var fullMark =$("#task-full-mark").text();
        var contents = [];
        var scoreItems = [];
        var courseTargets = [];
        if ($("#isSelect").val()=="true") {
            //选择题
            var elements = document.getElementsByClassName("option");
            for (var i = 0; i < elements.length; i++) {
                var td = elements[i].getElementsByTagName("td");
                var num = td[0].getElementsByTagName("span")[0].textContent;
                var content = td[1].getElementsByTagName("input")[0].value;
                var item = {
                    // num: String.fromCharCode(i + 65),
                    num:num,
                    item: content
                }
                console.log(item);
                contents.push(item);
            }
        } else {
            //非选择题
            var elements = document.getElementsByClassName("scoreItem");
            for (var i = 0; i < elements.length; i++) {
                var td = elements[i].getElementsByTagName("td");
                var scoreItem = td[0].getElementsByTagName("input")[0].value;
                var weight = td[1].getElementsByTagName("input")[0].value;
                var item = {
                    scoreItem: scoreItem,
                    weight: weight
                }
                scoreItems.push(item);
            }

        }
        var courseTargetId = $("#courseTarget-list input[name='courseTargetId']");
        var courseTargetWeight = $("#courseTarget-list input[name='weight']");
        for (var i = 0; i < courseTargetId.length; i++) {

            var item = {
                courseTargetId: courseTargetId[i].value,
                weight: parseFloat(courseTargetWeight[i].value)
            };
            courseTargets.push(item);
        }

        var json = {
            id: id,
            title: title,
            description: description,
            standardAnswer: standardAnswer,
            type: type,
            //新加
            fullMark: fullMark,
            isSelect: isSelect,
            content: contents,
            scoreItems: scoreItems,
            courseTargets: courseTargets
        }

        console.log(json);

        var url = "";
        url = CONTEXT_PATH + "task/ajaxUpdate";
        $.post(url, {
            data: JSON.stringify(json)
        }, function (data) {
            if (data.status == "success") {
                layer.msg("保存成功");
                window.location.reload();
            } else {
                layer.msg(data.message);
            }
        });
    }
</script>
</html>
